<template>
	<view class="init">
		<view class="container">
			<view v-if="items.length === 0" class="loading">加载中...</view>
			<swiper v-else class="swiper" :style="{ height: swiperHeight + 'px' }" @change="onSwiperChange"
				:current="activeIndex" previous-margin="20px" next-margin="20px">
				<swiper-item v-for="(item, index) in items" :key="index">
					<header>
						<view class="date">
							<text class="day">{{ convertTimestamp(item.date_by_day).dayOfMonth }}</text>
							<view class="sub-date">
								<text class="weekday">{{ convertTimestamp(item.date_by_day).dayOfWeek }}</text>
								<text class="lunar-date">{{ convertTimestamp(item.date_by_day).lunarDate }}</text>
							</view>
						</view>
						<!-- <view class="more">
							<text class="dot"></text>
							<text class="span">点击阅读更多</text>
						</view> -->
					</header>
					<view class="section" :id="'swiper-item-' + index">
						<view class="article">
							<text class="title">{{ item.title }}</text>
							<text class="content">{{ item.article }}</text>
							<view class="footer">
								<view class="stats">111</view>
								<view class="read-more" @click="gotoArticle(item.id)">阅读</view>
							</view>
						</view>
					</view>
				</swiper-item>

				<!-- 后一天日期 -->
				<swiper-item class="last">
					<header>
						<view class="date">
							<text class="day">{{ convertTimestamp(formattedNextDate).dayOfMonth }}</text>
							<view class="sub-date">
								<text class="weekday">{{ convertTimestamp(formattedNextDate).dayOfWeek }}</text>
								<text class="lunar-date">{{ convertTimestamp(formattedNextDate).lunarDate }}</text>
							</view>
						</view>
					</header>
					<view class="section">
						<view class="article">
							<!-- <text class="title">{{ item.title }}</text> -->
							<text class="content">{{ formattedCommingDate }}</text>
							<view class="footer">
								<view class="stats">距明日更新还有</view>
								<view class="read-more">{{ timeToUpdate }}</view>
							</view>
						</view>
					</view>



				</swiper-item>



			</swiper>
		</view>
		<tab />


	</view>
</template>
<script setup>
import { onLoad } from "@dcloudio/uni-app";
import { getIndexList } from "@/api/index.js";
import {
	getCurrentTimestamp,
	getCurrentFormattedDate,
	getLastNDays,
	convertTimestamp,
} from "@/util/index.js";
import tab from "/components/tab/tab.vue";
import { ref, onMounted, nextTick, computed, onBeforeUnmount, reactive } from "vue";
const items = ref([]);


// 新增当前活动索引
const activeIndex = ref(0);
const currentTimestamp = ref(Date.now());
const formattedNextDate = computed(() => {
	const currentDate = new Date(currentTimestamp.value);
	// 新增日期计算逻辑
	const nextDay = new Date(currentDate);
	nextDay.setDate(currentDate.getDate() + 1); // 增加1天
	const year = nextDay.getFullYear();
	const month = String(nextDay.getMonth() + 1).padStart(2, '0');
	const day = String(nextDay.getDate()).padStart(2, '0');
	return `${year}${month}${day}`;
});


const formattedCommingDate = computed(() => {
	const currentDate = new Date(currentTimestamp.value);
	const nextDay = new Date(currentDate);
	nextDay.setDate(currentDate.getDate() + 1);
	// 修改日期格式处理部分
	const month = String(nextDay.getMonth() + 1).padStart(2, '0'); // 保证两位月份
	const day = String(nextDay.getDate()); // 日期不需要补零
	return `${month}/${day}`; // 输出格式为 03/7
});

const timeToUpdate = computed(() => {
	// 获取当前时间
	const now = new Date(currentTimestamp.value);
	// 计算第二天凌晨时间
	const tomorrow = new Date(now);
	tomorrow.setDate(now.getDate() + 1);
	tomorrow.setHours(0, 0, 0, 0);

	// 计算时间差（毫秒）
	const diff = tomorrow - now;

	// 处理时间差为负数的情况（当超过次日零点时）
	const validDiff = diff > 0 ? diff : diff + 86400000; // 86400000=24*60*60*1000

	// 转换时间格式
	const hours = Math.floor(validDiff / 3600000).toString().padStart(2, '0');
	const minutes = Math.floor((validDiff % 3600000) / 60000).toString().padStart(2, '0');
	const seconds = Math.floor((validDiff % 60000) / 1000).toString().padStart(2, '0');

	return `${hours}时${minutes}分${seconds}秒`;
});



onLoad(async () => {
	try {

		uni.showLoading({ title: '加载中...', mask: true });

		const res = await getIndexList(getLastNDays(9)[8], getCurrentFormattedDate());

		if (Array.isArray(res)) {
			items.value = JSON.parse(JSON.stringify(res)).map(item => ({
				...item,
				created_at: Number(item.created_at)
			}));
			// 设置初始显示最后一个项目
			activeIndex.value = items.value.length - 1;

			uni.hideLoading();
			nextTick(() => {
				calculateSwiperHeight(activeIndex.value);
			});
		}
	} catch (e) {
		console.error("数据请求失败:", e);
	}
});
// 当前 swiper 高度
const swiperHeight = ref(0);
// 计算 swiper-item 高度
const calculateSwiperHeight = (index) => {
	uni.createSelectorQuery()
		.select(`#swiper-item-${index}`)
		.boundingClientRect(rect => {
			// console.log('元素尺寸信息:', rect);
			if (rect && rect.height > 0) {
				swiperHeight.value = rect.height + 40; /* 增加安全边距 */
			} else {
				setTimeout(() => calculateSwiperHeight(index), 300); /* 重试机制 */
			}
		}).exec()
}
// 监听 swiper 切换事件
const onSwiperChange = (event) => {
	const currentIndex = event.detail.current;
	calculateSwiperHeight(currentIndex);
};

let timer;

// 初始化时计算第一个 swiper-item 的高度
onMounted(() => {
	calculateSwiperHeight(0);
	timer = setInterval(() => {
		currentTimestamp.value = Date.now();
	}, 1000); // 60秒更新一次
});

onBeforeUnmount(() => {
	clearInterval(timer);
});


const gotoArticle = (articleId) => {
	uni.navigateTo({
		url: `/pages/article/article?articleId=${articleId}`
	});
};
</script>
<style lang="scss" scoped>
.init {
	font-family: Arial, sans-serif;
	background-color: #e6f7ef;
	margin: 0;
	padding: 0;
	padding-top: env(safe-area-inset-top, 20px);
	/* 兼容状态栏高度 */
	display: flex;
	justify-content: center;
	align-items: center;
	height: 100vh;
	width: 100vw;
}

.container {
	position: relative;
	margin-top: env(safe-area-inset-top, 20px);
	width: 100%;
	/* margin-top: 0px; */
	padding: 0 10px;
	background-color: white;
	border-radius: 12px;
	overflow: hidden;
	background-color: #e6f7ef;
}

.loading {
	position: absolute;
	top: 50%;
	left: 50%;
	transform: translate(-50%, -50%);
}


header {
	display: flex;
	justify-content: flex-start;
	align-items: center;
	padding: 0 16px 16px 40px;
	background-color: #e6f7ef;
}

.swiper {
	width: 100%;
	min-height: 600px;
	/* 添加最小高度 */
	overflow: visible;

	.last {
		width: 100%;

		.section {
			width: 100%;

			.article {
				width: 100%;
				position: relative;

				.content {
					position: absolute;
					top: 50%;
					left: 50%;
					transform: translate(-50%, -50%);
					width: 100%;
					display: flex;
					align-items: center;
					justify-content: center;

				}

			}



		}






	}



}

.date {
	display: flex;
	align-items: center;
}

.day {
	font-size: 48px;
	color: #333;
	margin-right: 16px;
}

.sub-date {
	display: flex;
	flex-direction: column;
	justify-content: center;
	align-items: flex-start;
	height: 100%;
}

.weekday,
.lunar-date {
	font-size: 16px;
	color: #666;
	line-height: 1.5;
}

.more {
	display: flex;
	align-items: center;
	color: #ffa500;
}

.dot {
	width: 8px;
	height: 8px;
	background-color: #ffa500;
	border-radius: 50%;
	margin-right: 8px;
}

.span {
	font-size: 16px;
}

.section {
	padding: 10px;
	box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
	background-color: #fff;
	border-radius: 12px;
	width: calc(100% - 20px);
	height: 450px;
	/* 减去左右各 30px 的间距 */
	margin-left: auto;
	margin-right: auto;
	transform: translateZ(0);
}

.article {
	height: 100%;
	position: relative;
}

.title {
	-webkit-writing-mode: vertical-lr;
	writing-mode: vertical-lr;
	text-orientation: upright;
	font-size: 24px;
	line-height: 1.5;
	letter-spacing: 4px;
	color: #333;
	text-align: right;
	margin: 0 0 50px auto;
	display: block;
}

.content {
	font-size: 16px;
	line-height: 1.5;
	margin-bottom: 30px;
	/* position: absolute;
	bottom: 0;
	left: 0; */
	width: 100%;
	/* 新增多行截断样式 */
	display: -webkit-box;
	-webkit-box-orient: vertical;
	-webkit-line-clamp: 7;
	overflow: hidden;
	text-overflow: ellipsis;
	max-height: calc(1.5em * 7);
	/* 根据行高计算最大高度 */
}

.footer {
	display: flex;
	justify-content: space-between;
	align-items: center;
	position: absolute;
	bottom: 0;
	left: 0;
	width: 100%;
	/* padding-bottom: 10px; */
}

.stats {
	color: #666;
}

.read-more {
	background-color: #ffa500;
	color: #fff;
	border: none;
	padding: 8px 16px;
	border-radius: 24px;
	cursor: pointer;
}
</style>
